<?php
/**
 * Array related utility functions.
 * 
 * @author Sergey Kuznetsov <clk824@gmail.com>
 */

namespace clk824;

/**
 * Put value to the array by string path.
 *
 * @param  Array  &$array
 * @param  string	 $path
 * @param  mixed  $value
 * @param  string	 $delimiter
 * @return void
 */
function array_put(&$array, $path, $value = null, $delimiter = "/")
{
	$item = &$array;
	$path = explode($delimiter, $path);
	$id = array_pop($path);
	foreach ($path as $key) {
		if (!(array_key_exists($key, $item) && is_array($item[$key])))
		{
			$item[$key] = [];
		}

		$item = &$item[$key];
	}

	if ($value !== null)
	{
		$item[$id] = $value;
	}
	else
	{
		unset($item[$id]);
	}
}

/**
 * Get value from the array by string path.
 *
 * @param  Array  $array
 * @param  string	 $path
 * @param  string	 $delimiter
 * @return mixed
 */
function array_get($array, $path, $delimiter = "/")
{
	$item = $array;
	$path = explode($delimiter, $path);
	foreach ($path as $key) {
		if (array_key_exists($key, $item))
		{
			$item = $item[$key];
		}
		else
		{
			throw new \Exception("Element of array with key '$key' not found");
		}
	}

	return $item;
}